"""
Alpha101因子库性能优化和验证测试
===============================

专门用于验证性能优化功能的测试脚本，包括：
1. Numba JIT编译验证
2. 内存使用优化测试
3. 并行计算验证
4. 大规模数据性能测试
5. 生产环境模拟
"""

import numpy as np
import pandas as pd
import time
import psutil
import os
import sys
import warnings
from typing import Dict, List, Tuple, Any
import json
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import threading

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from alpha101.core import Alpha101Factory
from alpha101.config import ALPHA_CONFIG
from engine.accelerator import NumbaAccelerator
from engine.memory import MemoryManager, get_memory_manager
from engine.calculator import FactorCalculator

# 忽略警告
warnings.filterwarnings('ignore')


class PerformanceOptimizationTester:
    """性能优化测试器"""
    
    def __init__(self):
        self.results = {}
        self.memory_manager = get_memory_manager()
        self.accelerator = NumbaAccelerator()
        
    def generate_test_data(self, n_stocks: int, n_days: int) -> Dict[str, np.ndarray]:
        """生成测试数据"""
        print(f"生成测试数据: {n_stocks}只股票, {n_days}个交易日")
        
        np.random.seed(42)
        
        # 生成基础价格数据
        base_price = 100.0
        returns = np.random.normal(0.0005, 0.02, (n_stocks, n_days))
        
        # 生成价格序列
        prices = np.zeros((n_stocks, n_days))
        prices[:, 0] = base_price * (1 + np.random.normal(0, 0.1, n_stocks))
        
        for i in range(1, n_days):
            prices[:, i] = prices[:, i-1] * (1 + returns[:, i])
        
        # 生成OHLC数据
        close = prices
        open_price = np.zeros_like(close)
        open_price[:, 0] = close[:, 0] * (1 + np.random.normal(0, 0.005, n_stocks))
        for i in range(1, n_days):
            overnight_return = np.random.normal(0, 0.003, n_stocks)
            open_price[:, i] = close[:, i-1] * (1 + overnight_return)
        
        intraday_volatility = np.random.uniform(0.005, 0.03, (n_stocks, n_days))
        high = np.maximum(open_price, close) * (1 + intraday_volatility)
        low = np.minimum(open_price, close) * (1 - intraday_volatility)
        
        # 确保价格关系正确
        low = np.minimum(low, np.minimum(open_price, close))
        high = np.maximum(high, np.maximum(open_price, close))
        
        # 生成成交量数据
        price_volatility = np.abs(returns)
        base_volume = np.random.lognormal(10, 1, (n_stocks, n_days))
        volume_multiplier = 1 + 2 * price_volatility
        volume = base_volume * volume_multiplier
        
        # 生成VWAP数据
        typical_price = (high + low + close) / 3.0
        vwap = typical_price + np.random.normal(0, 0.001, (n_stocks, n_days))
        vwap = np.clip(vwap, low * 1.001, high * 0.999)
        
        # 计算收益率
        returns_data = np.zeros((n_stocks, n_days))
        returns_data[:, 1:] = (close[:, 1:] - close[:, :-1]) / close[:, :-1]
        
        # 计算20日平均成交量
        adv20 = np.zeros((n_stocks, n_days))
        for i in range(19, n_days):
            adv20[:, i] = np.mean(volume[:, i-19:i+1], axis=1)
        adv20[:, :19] = np.nan
        
        return {
            'open': open_price,
            'high': high,
            'low': low,
            'close': close,
            'volume': volume,
            'vwap': vwap,
            'returns': returns_data,
            'adv20': adv20
        }
    
    def test_numba_acceleration(self) -> Dict[str, Any]:
        """测试Numba JIT编译加速效果"""
        print("\n" + "="*60)
        print("测试Numba JIT编译加速效果")
        print("="*60)
        
        # 生成测试数据
        data = self.generate_test_data(100, 252)
        
        # 测试因子列表
        test_factors = ['alpha001', 'alpha002', 'alpha003', 'alpha004', 'alpha005']
        
        results = {
            'numba_available': self.accelerator.is_numba_available(),
            'numba_info': self.accelerator.get_numba_info(),
            'factor_tests': {}
        }
        
        for factor_id in test_factors:
            print(f"\n测试因子 {factor_id}:")
            
            # 不使用Numba的测试
            factory_no_numba = Alpha101Factory(use_numba=False)
            start_time = time.time()
            result_no_numba = factory_no_numba.compute_factor(factor_id, data)
            time_no_numba = time.time() - start_time
            
            # 使用Numba的测试
            factory_with_numba = Alpha101Factory(use_numba=True)
            start_time = time.time()
            result_with_numba = factory_with_numba.compute_factor(factor_id, data)
            time_with_numba = time.time() - start_time
            
            # 验证结果一致性
            if result_no_numba is not None and result_with_numba is not None:
                # 计算相关性来验证结果一致性
                valid_mask = np.isfinite(result_no_numba) & np.isfinite(result_with_numba)
                if np.sum(valid_mask) > 100:
                    correlation = np.corrcoef(
                        result_no_numba[valid_mask].flatten(),
                        result_with_numba[valid_mask].flatten()
                    )[0, 1]
                else:
                    correlation = np.nan
            else:
                correlation = np.nan
            
            # 计算加速比
            speedup = time_no_numba / time_with_numba if time_with_numba > 0 else 0
            
            factor_result = {
                'time_no_numba': time_no_numba,
                'time_with_numba': time_with_numba,
                'speedup': speedup,
                'correlation': correlation,
                'success': correlation > 0.95 if not np.isnan(correlation) else False
            }
            
            results['factor_tests'][factor_id] = factor_result
            
            print(f"  不使用Numba: {time_no_numba:.4f}秒")
            print(f"  使用Numba: {time_with_numba:.4f}秒")
            print(f"  加速比: {speedup:.2f}x")
            print(f"  结果相关性: {correlation:.4f}")
            print(f"  测试结果: {'✓' if factor_result['success'] else '✗'}")
        
        # 计算总体统计
        successful_tests = [t for t in results['factor_tests'].values() if t['success']]
        if successful_tests:
            avg_speedup = np.mean([t['speedup'] for t in successful_tests])
            avg_correlation = np.mean([t['correlation'] for t in successful_tests])
        else:
            avg_speedup = 0
            avg_correlation = 0
        
        results['summary'] = {
            'total_tests': len(test_factors),
            'successful_tests': len(successful_tests),
            'success_rate': len(successful_tests) / len(test_factors),
            'average_speedup': avg_speedup,
            'average_correlation': avg_correlation
        }
        
        print(f"\n总体结果:")
        print(f"  测试因子数: {results['summary']['total_tests']}")
        print(f"  成功测试数: {results['summary']['successful_tests']}")
        print(f"  成功率: {results['summary']['success_rate']:.1%}")
        print(f"  平均加速比: {results['summary']['average_speedup']:.2f}x")
        print(f"  平均相关性: {results['summary']['average_correlation']:.4f}")
        
        return results
    
    def test_memory_optimization(self) -> Dict[str, Any]:
        """测试内存使用优化"""
        print("\n" + "="*60)
        print("测试内存使用优化")
        print("="*60)
        
        # 重置内存管理器
        self.memory_manager.clear_buffer_pool()
        self.memory_manager.garbage_collect()
        
        # 记录初始内存状态
        initial_memory = self.memory_manager.monitor_memory_usage()
        print(f"初始内存使用: {initial_memory['current_memory_mb']:.2f} MB")
        
        results = {
            'initial_memory_mb': initial_memory['current_memory_mb'],
            'memory_tests': [],
            'buffer_pool_tests': []
        }
        
        # 测试不同数据规模下的内存使用
        test_sizes = [(50, 100), (100, 252), (200, 500)]
        
        for n_stocks, n_days in test_sizes:
            print(f"\n测试数据规模: {n_stocks}只股票 × {n_days}天")
            
            # 生成测试数据
            data = self.generate_test_data(n_stocks, n_days)
            
            # 记录数据生成后的内存
            after_data_memory = self.memory_manager.monitor_memory_usage()
            
            # 计算一些因子
            factory = Alpha101Factory(use_numba=True)
            test_factors = ['alpha001', 'alpha002', 'alpha003']
            
            factor_results = []
            after_factor_memory = after_data_memory  # 初始化变量
            
            for factor_id in test_factors:
                before_factor_memory = self.memory_manager.monitor_memory_usage()
                
                try:
                    result = factory.compute_factor(factor_id, data)
                    success = result is not None
                except Exception as e:
                    success = False
                
                after_factor_memory = self.memory_manager.monitor_memory_usage()
                
                factor_results.append({
                    'factor_id': factor_id,
                    'success': success,
                    'memory_before_mb': before_factor_memory['current_memory_mb'],
                    'memory_after_mb': after_factor_memory['current_memory_mb'],
                    'memory_increase_mb': after_factor_memory['current_memory_mb'] - before_factor_memory['current_memory_mb']
                })
            
            # 执行垃圾回收
            collected = self.memory_manager.garbage_collect()
            after_gc_memory = self.memory_manager.monitor_memory_usage()
            
            test_result = {
                'data_size': (n_stocks, n_days),
                'memory_after_data_mb': after_data_memory['current_memory_mb'],
                'memory_after_factors_mb': after_factor_memory['current_memory_mb'],
                'memory_after_gc_mb': after_gc_memory['current_memory_mb'],
                'memory_increase_mb': after_factor_memory['current_memory_mb'] - initial_memory['current_memory_mb'],
                'memory_recovered_mb': after_factor_memory['current_memory_mb'] - after_gc_memory['current_memory_mb'],
                'factor_results': factor_results,
                'gc_collected': collected
            }
            
            results['memory_tests'].append(test_result)
            
            print(f"  数据生成后内存: {after_data_memory['current_memory_mb']:.2f} MB")
            print(f"  因子计算后内存: {after_factor_memory['current_memory_mb']:.2f} MB")
            print(f"  垃圾回收后内存: {after_gc_memory['current_memory_mb']:.2f} MB")
            print(f"  内存增长: {test_result['memory_increase_mb']:.2f} MB")
            print(f"  内存回收: {test_result['memory_recovered_mb']:.2f} MB")
            print(f"  垃圾回收对象数: {collected}")
        
        # 测试缓冲池功能
        print(f"\n测试缓冲池功能:")
        
        # 分配一些缓冲区
        buffer1 = self.memory_manager.allocate_buffers((100, 252), np.dtype(np.float64))
        buffer2 = self.memory_manager.allocate_buffers((100, 252), np.dtype(np.float64))
        buffer3 = self.memory_manager.allocate_buffers((50, 100), np.dtype(np.float32))
        
        pool_info_after_alloc = self.memory_manager.get_buffer_pool_info()
        
        # 回收缓冲区
        self.memory_manager.reuse_arrays([buffer1, buffer2, buffer3])
        
        pool_info_after_reuse = self.memory_manager.get_buffer_pool_info()
        
        # 再次分配相同大小的缓冲区（应该从池中获取）
        buffer4 = self.memory_manager.allocate_buffers((100, 252), np.dtype(np.float64))
        buffer5 = self.memory_manager.allocate_buffers((100, 252), np.dtype(np.float64))
        
        pool_info_after_realloc = self.memory_manager.get_buffer_pool_info()
        
        buffer_test_result = {
            'pool_after_alloc': pool_info_after_alloc,
            'pool_after_reuse': pool_info_after_reuse,
            'pool_after_realloc': pool_info_after_realloc
        }
        
        results['buffer_pool_tests'].append(buffer_test_result)
        
        print(f"  分配后缓冲池: {pool_info_after_alloc['total_buffers']} 个缓冲区")
        print(f"  回收后缓冲池: {pool_info_after_reuse['total_buffers']} 个缓冲区")
        print(f"  重新分配后缓冲池: {pool_info_after_realloc['total_buffers']} 个缓冲区")
        
        # 获取内存优化建议
        optimization_suggestions = self.memory_manager.suggest_memory_optimization()
        results['optimization_suggestions'] = optimization_suggestions
        
        print(f"\n内存优化建议:")
        for suggestion in optimization_suggestions['suggestions']:
            print(f"  - {suggestion}")
        print(f"  优化分数: {optimization_suggestions['optimization_score']:.1f}/100")
        
        return results
    
    def test_parallel_computing(self) -> Dict[str, Any]:
        """测试并行计算功能"""
        print("\n" + "="*60)
        print("测试并行计算功能")
        print("="*60)
        
        # 生成测试数据
        data = self.generate_test_data(200, 252)
        
        results = {
            'system_info': {
                'cpu_count': os.cpu_count(),
                'thread_count': threading.active_count()
            },
            'parallel_tests': []
        }
        
        print(f"系统信息:")
        print(f"  CPU核心数: {results['system_info']['cpu_count']}")
        print(f"  当前线程数: {results['system_info']['thread_count']}")
        
        # 测试因子列表
        test_factors = ['alpha001', 'alpha002', 'alpha003', 'alpha004', 'alpha005']
        
        # 串行计算测试
        print(f"\n串行计算测试:")
        factory = Alpha101Factory(use_numba=True)
        
        start_time = time.time()
        serial_results = {}
        for factor_id in test_factors:
            try:
                result = factory.compute_factor(factor_id, data)
                serial_results[factor_id] = result
            except Exception as e:
                print(f"  {factor_id} 计算失败: {str(e)}")
                serial_results[factor_id] = None
        serial_time = time.time() - start_time
        
        print(f"  串行计算时间: {serial_time:.4f}秒")
        print(f"  成功计算因子数: {sum(1 for r in serial_results.values() if r is not None)}")
        
        # 并行计算测试（线程池）
        print(f"\n并行计算测试（线程池）:")
        
        def compute_factor_wrapper(factor_id):
            try:
                factory_local = Alpha101Factory(use_numba=True)
                return factor_id, factory_local.compute_factor(factor_id, data)
            except Exception as e:
                return factor_id, None
        
        start_time = time.time()
        cpu_count = os.cpu_count() or 4
        with ThreadPoolExecutor(max_workers=min(4, cpu_count)) as executor:
            parallel_results_thread = dict(executor.map(
                lambda fid: compute_factor_wrapper(fid), test_factors
            ))
        parallel_time_thread = time.time() - start_time
        
        print(f"  线程池计算时间: {parallel_time_thread:.4f}秒")
        print(f"  成功计算因子数: {sum(1 for r in parallel_results_thread.values() if r is not None)}")
        print(f"  加速比: {serial_time / parallel_time_thread:.2f}x")
        
        # 验证结果一致性
        consistency_check = {}
        for factor_id in test_factors:
            serial_result = serial_results.get(factor_id)
            parallel_result = parallel_results_thread.get(factor_id)
            
            if serial_result is not None and parallel_result is not None:
                valid_mask = np.isfinite(serial_result) & np.isfinite(parallel_result)
                if np.sum(valid_mask) > 100:
                    correlation = np.corrcoef(
                        serial_result[valid_mask].flatten(),
                        parallel_result[valid_mask].flatten()
                    )[0, 1]
                else:
                    correlation = np.nan
            else:
                correlation = np.nan
            
            consistency_check[factor_id] = correlation
        
        avg_correlation = np.nanmean(list(consistency_check.values()))
        
        parallel_test_result = {
            'test_type': 'thread_pool',
            'serial_time': serial_time,
            'parallel_time': parallel_time_thread,
            'speedup': serial_time / parallel_time_thread,
            'consistency_check': consistency_check,
            'average_correlation': avg_correlation,
            'success': avg_correlation > 0.95 if not np.isnan(avg_correlation) else False
        }
        
        results['parallel_tests'].append(parallel_test_result)
        
        print(f"  结果一致性检查:")
        for factor_id, corr in consistency_check.items():
            print(f"    {factor_id}: {corr:.4f}")
        print(f"  平均相关性: {avg_correlation:.4f}")
        
        return results
    
    def test_large_scale_performance(self) -> Dict[str, Any]:
        """测试大规模数据性能"""
        print("\n" + "="*60)
        print("测试大规模数据性能")
        print("="*60)
        
        results = {
            'scale_tests': []
        }
        
        # 不同规模的测试
        test_scales = [
            (100, 252, "小规模"),
            (500, 252, "中规模"),
            (1000, 252, "大规模"),
            (1000, 500, "超大规模")
        ]
        
        test_factors = ['alpha001', 'alpha002', 'alpha003']
        
        for n_stocks, n_days, scale_name in test_scales:
            print(f"\n{scale_name}测试: {n_stocks}只股票 × {n_days}天")
            
            # 检查内存限制
            estimated_memory_mb = (n_stocks * n_days * 8 * 10) / (1024 * 1024)  # 估算内存需求
            print(f"  估算内存需求: {estimated_memory_mb:.2f} MB")
            
            current_memory = self.memory_manager.monitor_memory_usage()
            if current_memory['available_memory_mb'] < estimated_memory_mb:
                print(f"  ⚠️ 内存不足，跳过此规模测试")
                continue
            
            try:
                # 生成测试数据
                data_start_time = time.time()
                data = self.generate_test_data(n_stocks, n_days)
                data_generation_time = time.time() - data_start_time
                
                # 记录数据生成后的内存
                memory_after_data = self.memory_manager.monitor_memory_usage()
                
                # 测试因子计算
                factory = Alpha101Factory(use_numba=True)
                
                factor_times = {}
                total_computation_time = 0
                
                for factor_id in test_factors:
                    factor_start_time = time.time()
                    try:
                        result = factory.compute_factor(factor_id, data)
                        factor_time = time.time() - factor_start_time
                        factor_times[factor_id] = {
                            'time': factor_time,
                            'success': result is not None,
                            'valid_ratio': np.sum(np.isfinite(result)) / result.size if result is not None else 0
                        }
                        total_computation_time += factor_time
                        
                        print(f"    {factor_id}: {factor_time:.4f}秒 (有效值: {factor_times[factor_id]['valid_ratio']:.1%})")
                        
                    except Exception as e:
                        factor_times[factor_id] = {
                            'time': 0,
                            'success': False,
                            'error': str(e),
                            'valid_ratio': 0
                        }
                        print(f"    {factor_id}: 失败 - {str(e)}")
                
                # 记录计算后的内存
                memory_after_computation = self.memory_manager.monitor_memory_usage()
                
                # 计算性能指标
                data_size_mb = sum(arr.nbytes for arr in data.values()) / (1024 * 1024)
                throughput_factors_per_sec = len(test_factors) / total_computation_time if total_computation_time > 0 else 0
                throughput_data_points_per_sec = (n_stocks * n_days * len(test_factors)) / total_computation_time if total_computation_time > 0 else 0
                
                scale_test_result = {
                    'scale_name': scale_name,
                    'n_stocks': n_stocks,
                    'n_days': n_days,
                    'data_generation_time': data_generation_time,
                    'total_computation_time': total_computation_time,
                    'factor_times': factor_times,
                    'data_size_mb': data_size_mb,
                    'memory_after_data_mb': memory_after_data['current_memory_mb'],
                    'memory_after_computation_mb': memory_after_computation['current_memory_mb'],
                    'memory_increase_mb': memory_after_computation['current_memory_mb'] - current_memory['current_memory_mb'],
                    'throughput_factors_per_sec': throughput_factors_per_sec,
                    'throughput_data_points_per_sec': throughput_data_points_per_sec,
                    'success_rate': sum(1 for ft in factor_times.values() if ft['success']) / len(test_factors)
                }
                
                results['scale_tests'].append(scale_test_result)
                
                print(f"  数据生成时间: {data_generation_time:.4f}秒")
                print(f"  总计算时间: {total_computation_time:.4f}秒")
                print(f"  数据大小: {data_size_mb:.2f} MB")
                print(f"  内存增长: {scale_test_result['memory_increase_mb']:.2f} MB")
                print(f"  吞吐量: {throughput_factors_per_sec:.2f} 因子/秒")
                print(f"  成功率: {scale_test_result['success_rate']:.1%}")
                
                # 清理内存
                del data
                self.memory_manager.garbage_collect()
                
            except Exception as e:
                print(f"  ❌ 测试失败: {str(e)}")
                scale_test_result = {
                    'scale_name': scale_name,
                    'n_stocks': n_stocks,
                    'n_days': n_days,
                    'error': str(e),
                    'success': False
                }
                results['scale_tests'].append(scale_test_result)
        
        return results
    
    def test_production_simulation(self) -> Dict[str, Any]:
        """模拟生产环境测试"""
        print("\n" + "="*60)
        print("模拟生产环境测试")
        print("="*60)
        
        results = {
            'stability_test': {},
            'stress_test': {},
            'error_handling_test': {}
        }
        
        # 稳定性测试：连续运行多次
        print(f"\n稳定性测试：连续运行50次小规模计算")
        
        data = self.generate_test_data(50, 100)
        factory = Alpha101Factory(use_numba=True)
        
        stability_times = []
        stability_errors = []
        memory_usage = []
        
        for i in range(50):
            try:
                start_time = time.time()
                result = factory.compute_factor('alpha001', data)
                computation_time = time.time() - start_time
                stability_times.append(computation_time)
                
                # 记录内存使用
                memory_info = self.memory_manager.monitor_memory_usage()
                memory_usage.append(memory_info['current_memory_mb'])
                
                if i % 10 == 0:
                    print(f"  第{i+1}次: {computation_time:.4f}秒, 内存: {memory_info['current_memory_mb']:.2f}MB")
                
            except Exception as e:
                stability_errors.append(str(e))
                print(f"  第{i+1}次: 失败 - {str(e)}")
        
        results['stability_test'] = {
            'total_runs': 50,
            'successful_runs': len(stability_times),
            'error_count': len(stability_errors),
            'success_rate': len(stability_times) / 50,
            'average_time': np.mean(stability_times) if stability_times else 0,
            'time_std': np.std(stability_times) if stability_times else 0,
            'min_time': np.min(stability_times) if stability_times else 0,
            'max_time': np.max(stability_times) if stability_times else 0,
            'memory_trend': {
                'initial_mb': memory_usage[0] if memory_usage else 0,
                'final_mb': memory_usage[-1] if memory_usage else 0,
                'max_mb': np.max(memory_usage) if memory_usage else 0,
                'memory_leak_mb': memory_usage[-1] - memory_usage[0] if len(memory_usage) >= 2 else 0
            },
            'errors': stability_errors
        }
        
        print(f"  成功率: {results['stability_test']['success_rate']:.1%}")
        print(f"  平均时间: {results['stability_test']['average_time']:.4f}±{results['stability_test']['time_std']:.4f}秒")
        print(f"  内存变化: {results['stability_test']['memory_trend']['memory_leak_mb']:.2f}MB")
        
        # 压力测试：同时计算多个因子
        print(f"\n压力测试：同时计算20个因子")
        
        stress_factors = [f'alpha{i:03d}' for i in range(1, 21)]
        data_stress = self.generate_test_data(100, 252)
        
        stress_start_time = time.time()
        stress_results = {}
        stress_errors = []
        
        for factor_id in stress_factors:
            try:
                result = factory.compute_factor(factor_id, data_stress)
                stress_results[factor_id] = result is not None
            except Exception as e:
                stress_results[factor_id] = False
                stress_errors.append(f"{factor_id}: {str(e)}")
        
        stress_total_time = time.time() - stress_start_time
        stress_memory = self.memory_manager.monitor_memory_usage()
        
        results['stress_test'] = {
            'total_factors': len(stress_factors),
            'successful_factors': sum(stress_results.values()),
            'success_rate': sum(stress_results.values()) / len(stress_factors),
            'total_time': stress_total_time,
            'memory_usage_mb': stress_memory['current_memory_mb'],
            'errors': stress_errors
        }
        
        print(f"  成功率: {results['stress_test']['success_rate']:.1%}")
        print(f"  总时间: {stress_total_time:.4f}秒")
        print(f"  内存使用: {stress_memory['current_memory_mb']:.2f}MB")
        print(f"  错误数量: {len(stress_errors)}")
        
        # 错误处理测试：测试异常情况
        print(f"\n错误处理测试：测试异常输入")
        
        error_test_cases = [
            ('invalid_factor', 'alpha999', data_stress),
            ('empty_data', 'alpha001', {}),
            ('wrong_shape', 'alpha001', {'close': np.array([1, 2, 3])}),
            ('nan_data', 'alpha001', {'close': np.full((10, 10), np.nan), 'volume': np.full((10, 10), np.nan)})
        ]
        
        error_handling_results = {}
        
        for test_name, factor_id, test_data in error_test_cases:
            try:
                result = factory.compute_factor(factor_id, test_data)
                error_handling_results[test_name] = {
                    'success': False,
                    'error': 'Should have failed but succeeded',
                    'result_type': type(result).__name__
                }
            except Exception as e:
                error_handling_results[test_name] = {
                    'success': True,
                    'error': str(e),
                    'error_type': type(e).__name__
                }
            
            print(f"  {test_name}: {'✓' if error_handling_results[test_name]['success'] else '✗'}")
        
        results['error_handling_test'] = error_handling_results
        
        return results
    
    def generate_performance_report(self) -> Dict[str, Any]:
        """生成综合性能报告"""
        print("\n" + "="*60)
        print("生成综合性能报告")
        print("="*60)
        
        # 运行所有测试
        numba_results = self.test_numba_acceleration()
        memory_results = self.test_memory_optimization()
        parallel_results = self.test_parallel_computing()
        scale_results = self.test_large_scale_performance()
        production_results = self.test_production_simulation()
        
        # 生成综合报告
        report = {
            'timestamp': pd.Timestamp.now().isoformat(),
            'system_info': {
                'cpu_count': os.cpu_count(),
                'memory_total_gb': psutil.virtual_memory().total / (1024**3),
                'python_version': sys.version,
                'numpy_version': np.__version__,
                'pandas_version': pd.__version__
            },
            'test_results': {
                'numba_acceleration': numba_results,
                'memory_optimization': memory_results,
                'parallel_computing': parallel_results,
                'large_scale_performance': scale_results,
                'production_simulation': production_results
            },
            'performance_summary': self._calculate_performance_summary(
                numba_results, memory_results, parallel_results, scale_results, production_results
            )
        }
        
        # 保存报告
        report_file = 'alpha101_performance_report.json'
        try:
            with open(report_file, 'w', encoding='utf-8') as f:
                json.dump(report, f, indent=2, ensure_ascii=False, default=str)
            print(f"\n性能报告已保存到: {report_file}")
        except Exception as e:
            print(f"\n保存报告失败: {e}")
        
        return report
    
    def _calculate_performance_summary(self, numba_results, memory_results,
                                     parallel_results, scale_results, production_results) -> Dict[str, Any]:
        """计算性能摘要"""
        summary = {
            'overall_score': 0,
            'numba_performance': {
                'available': numba_results.get('numba_available', False),
                'average_speedup': numba_results.get('summary', {}).get('average_speedup', 0),
                'success_rate': numba_results.get('summary', {}).get('success_rate', 0)
            },
            'memory_efficiency': {
                'optimization_score': 0,
                'memory_leak_detected': False
            },
            'parallel_efficiency': {
                'speedup': 0,
                'success_rate': 0
            },
            'scalability': {
                'max_scale_tested': '',
                'performance_degradation': 0
            },
            'stability': {
                'success_rate': production_results.get('stability_test', {}).get('success_rate', 0),
                'memory_leak_mb': production_results.get('stability_test', {}).get('memory_trend', {}).get('memory_leak_mb', 0)
            }
        }
        
        # 计算内存效率
        if memory_results.get('optimization_suggestions'):
            summary['memory_efficiency']['optimization_score'] = memory_results['optimization_suggestions'].get('optimization_score', 0)
        
        # 计算并行效率
        if parallel_results.get('parallel_tests'):
            parallel_test = parallel_results['parallel_tests'][0]
            summary['parallel_efficiency']['speedup'] = parallel_test.get('speedup', 0)
            summary['parallel_efficiency']['success_rate'] = 1.0 if parallel_test.get('success', False) else 0.0
        
        # 计算可扩展性
        if scale_results.get('scale_tests'):
            successful_tests = [t for t in scale_results['scale_tests'] if t.get('success_rate', 0) > 0.8]
            if successful_tests:
                largest_test = max(successful_tests, key=lambda x: x['n_stocks'] * x['n_days'])
                summary['scalability']['max_scale_tested'] = f"{largest_test['n_stocks']}×{largest_test['n_days']}"
        
        # 计算总体分数
        scores = [
            summary['numba_performance']['success_rate'] * 25,
            (summary['memory_efficiency']['optimization_score'] / 100) * 25,
            summary['parallel_efficiency']['success_rate'] * 25,
            summary['stability']['success_rate'] * 25
        ]
        summary['overall_score'] = sum(scores)
        
        return summary


def main():
    """主函数"""
    print("Alpha101因子库性能优化验证测试")
    print("=" * 60)
    
    tester = PerformanceOptimizationTester()
    
    try:
        # 生成综合性能报告
        report = tester.generate_performance_report()
        
        # 打印摘要
        summary = report['performance_summary']
        print(f"\n性能验证摘要:")
        print(f"  总体分数: {summary['overall_score']:.1f}/100")
        print(f"  Numba加速: {'✓' if summary['numba_performance']['available'] else '✗'} "
              f"(平均加速比: {summary['numba_performance']['average_speedup']:.2f}x)")
        print(f"  内存优化: {summary['memory_efficiency']['optimization_score']:.1f}/100")
        print(f"  并行计算: {'✓' if summary['parallel_efficiency']['success_rate'] > 0.8 else '✗'} "
              f"(加速比: {summary['parallel_efficiency']['speedup']:.2f}x)")
        print(f"  稳定性: {summary['stability']['success_rate']:.1%}")
        print(f"  最大测试规模: {summary['scalability']['max_scale_tested']}")
        
        # 性能目标验证
        print(f"\n性能目标验证:")
        targets_met = 0
        total_targets = 4
        
        # 目标1: Numba加速比 ≥ 3倍
        if summary['numba_performance']['average_speedup'] >= 3.0:
            print(f"  ✓ Numba加速比目标达成: {summary['numba_performance']['average_speedup']:.2f}x ≥ 3x")
            targets_met += 1
        else:
            print(f"  ✗ Numba加速比目标未达成: {summary['numba_performance']['average_speedup']:.2f}x < 3x")
        
        # 目标2: 内存优化分数 ≥ 80
        if summary['memory_efficiency']['optimization_score'] >= 80:
            print(f"  ✓ 内存优化目标达成: {summary['memory_efficiency']['optimization_score']:.1f} ≥ 80")
            targets_met += 1
        else:
            print(f"  ✗ 内存优化目标未达成: {summary['memory_efficiency']['optimization_score']:.1f} < 80")
        
        # 目标3: 并行计算加速比 ≥ 2倍
        if summary['parallel_efficiency']['speedup'] >= 2.0:
            print(f"  ✓ 并行计算目标达成: {summary['parallel_efficiency']['speedup']:.2f}x ≥ 2x")
            targets_met += 1
        else:
            print(f"  ✗ 并行计算目标未达成: {summary['parallel_efficiency']['speedup']:.2f}x < 2x")
        
        # 目标4: 稳定性 ≥ 95%
        if summary['stability']['success_rate'] >= 0.95:
            print(f"  ✓ 稳定性目标达成: {summary['stability']['success_rate']:.1%} ≥ 95%")
            targets_met += 1
        else:
            print(f"  ✗ 稳定性目标未达成: {summary['stability']['success_rate']:.1%} < 95%")
        
        print(f"\n目标达成情况: {targets_met}/{total_targets} ({targets_met/total_targets:.1%})")
        
        if targets_met >= 3:
            print("🎉 性能优化验证通过！Alpha101因子库已达到生产级别性能标准。")
        else:
            print("⚠️ 性能优化验证未完全通过，建议进一步优化。")
        
        return targets_met >= 3
        
    except Exception as e:
        print(f"性能测试过程中发生错误: {e}")
        import traceback
        traceback.print_exc()
        return False


if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)